#pragma once
#include<iostream>
#include<string>
#include<vector>
#include"Log.hpp"
#include"InetAddr.hpp"
#include"Mutex.hpp"

using namespace MutexModule;
using namespace LogModule;
using namespace InetAddrModule;

class Route
{
 private:
  bool IsExist(const InetAddr& peer)
  {
     for(auto& user:_online_user)
     {
        if(user == peer)
         return true;
     }
     return false;
  }

  void AddUser(const InetAddr& peer)
  {
    LOG(LogLevel::INFO) <<"新增一个在线用户： " << peer.StringAddr();
    _online_user.push_back(peer);
  }

  void DeleteUser(const InetAddr& peer)
  {
    for(auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
    {
        if(*iter == peer)
        {
            _online_user.erase(iter);
            break;
        }
    }
  }

   public:
    Route(){}
    
    void MessageRoute(int sockfd, const std::string& message, InetAddr& peer)
    {
        LockGurd lockguard(_mutex);
        if(!IsExist(peer))
        {
            AddUser(peer);
        }
        std::string send_message = peer.StringAddr() + "# " + message; //ip+#消息

        //发送消息
        for(auto& user:_online_user)
        {
            sendto(sockfd, send_message.c_str(), send_message.size(), 0, (const sockaddr*)&(user.NetAddr()),sizeof(user.NetAddr()));
        }

        if(message == "QUIT")
        {
            LOG(LogLevel::INFO) << "删除一个在线用户： " << peer.StringAddr();
            DeleteUser(peer);
        }
    }

    ~Route(){}
    private:
    //首次给我发消息，等同于登录
     std::vector<InetAddr> _online_user; //在线用户
     Mutex _mutex;
};